package com.berwin.bmfb.views;

import com.berwin.bmfb.entity.BMChar;
import com.berwin.bmfb.entity.BMFont;
import com.berwin.bmfb.utility.UserDefault;
import sun.rmi.rmic.Main;

import javax.imageio.ImageIO;
import javax.swing.*;
import javax.swing.filechooser.FileFilter;
import java.awt.*;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class CharsView extends BasePanel {

    private BMFont bmFont = null;

    private JList<String> listChar = null;
    private JPopupMenu popupMenu = null;

    public CharsView(MainView mainView, BMFont bmFont) {
        super(mainView);
        this.bmFont = bmFont;
        popupMenu = this.initPopupMenu();
        this.setLayout(new BorderLayout());
        this.listChar = new JList<String>();
        this.listChar.setListData(this.bmFont.toCharString());
        // 只能单选
        this.listChar.setSelectionMode(ListSelectionModel.SINGLE_INTERVAL_SELECTION);
        this.listChar.setVisibleRowCount(5);
        // 添加选项选中状态被改变的监听器
        final JList list = this.listChar;
        this.listChar.addListSelectionListener(e -> {
            // 获取所有被选中的选项索引
//            int[] indices = list.getSelectedIndices();
            // 获取选项数据的 ListModel
//            ListModel<String> listModel = list.getModel();
//            // 输出选中的选项
//            for (int index : indices) {
//                System.out.println("选中: " + index + " = " + listModel.getElementAt(index));
//            }
            if (list.getSelectedIndex() >= 0 && !this.isFromSelected) {
                CharsView.this.mainView.handleLetterSelected(list.getSelectedIndex());
            }
        });
        this.listChar.addMouseListener(new MouseAdapter() {
            @Override
            public void mouseClicked(MouseEvent e) {
                super.mouseClicked(e);
                if (e.getButton() == 3 && list.getSelectedIndex() >= 0) {
                    popupMenu.show(listChar, e.getX(), e.getY());
                    ((JMenuItem) popupMenu.getComponent(0)).setText("删除 \"" + listChar.getSelectedValue() + "\"");
                }
            }
        });

        // 设置默认选中项
        this.listChar.setSelectedIndex(0);
        JScrollPane scrollPane = new JScrollPane(this.listChar);
        this.add(scrollPane, BorderLayout.CENTER);
    }

    public JPopupMenu initPopupMenu() {
        JPopupMenu popupMenu = new JPopupMenu();
        JMenuItem itemDelete = new JMenuItem("删除");
        itemDelete.addActionListener(e -> {
            int result = JOptionPane.showConfirmDialog(this.mainView, "确认删除字符 \"" + this.listChar.getSelectedValue() + "\" 吗？");
            if (result == 0) {
                int idx = this.listChar.getSelectedIndex();
                this.bmFont.getBmChars().remove(idx);
                this.mainView.handleUpdate();
                this.listChar.setSelectedIndex(Math.max(idx, 0));
                this.mainView.handleDoLayoutChars();
            }
        });
        popupMenu.add(itemDelete);
        JMenuItem itemExport = new JMenuItem("导出PNG");
        itemExport.addActionListener(e -> {
            int idx = this.listChar.getSelectedIndex();
            BMChar bmChar = this.bmFont.getBmChars().get(idx);
            JFileChooser fileChooser = new JFileChooser(UserDefault.getInstance().getValueForKey(MainView.KEY_LAST_DIRECTORY, this.bmFont.getFilePath()));
            fileChooser.setFileFilter(new FileFilter() {
                @Override
                public boolean accept(File f) {
                    return f.getAbsolutePath().endsWith(".png");
                }

                @Override
                public String getDescription() {
                    return "PNG格式文件";
                }
            });
            fileChooser.setSelectedFile(new File(bmChar.getLetter() + ".png"));
            int i = fileChooser.showSaveDialog(this.mainView);
            if (i == JFileChooser.APPROVE_OPTION) {
                File selFile = fileChooser.getSelectedFile();
                String file = selFile.getAbsolutePath();
                if (!file.endsWith(".png")) {
                    file += ".png";
                    selFile = new File(file);
                }
                UserDefault.getInstance().setValueForKey(MainView.KEY_LAST_DIRECTORY, selFile.getParent());
                try {
                    Image image = bmChar.getImage();
                    // 获取 Image 对象的高度和宽度
                    int width = image.getWidth(null);
                    int height = image.getHeight(null);
                    BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
                    Graphics g = bi.getGraphics();
                    //通过 BufferedImage 绘制图像并保存在其对象中
                    g.drawImage(image, 0, 0, width, height, null);
                    g.dispose();
                    ImageIO.write(bi, "png", selFile);
                } catch (IOException e1) {
                    e1.printStackTrace();
                }
            }
        });
        popupMenu.add(itemExport);
        return popupMenu;
    }

    @Override
    public void onUpdate() {
        this.listChar.setListData(this.bmFont.toCharString());
    }

    @Override
    public void doLayoutChars() {
        super.doLayoutChars();
        this.listChar.setListData(this.bmFont.toCharString());
    }

    @Override
    public void onSelectLetter(int idx) {
        this.isFromSelected = true;
        this.giveUpListenValueChange = true;
        this.listChar.setSelectedIndex(idx);
        this.isFromSelected = false;
        this.giveUpListenValueChange = false;
        this.onValueChanged();
    }

    @Override
    public void onValueChanged() {

    }

    @Override
    public void onBMFontUpdated(BMFont bmFont) {
        this.bmFont = bmFont;
        this.giveUpListenValueChange = true;
        this.listChar.setListData(this.bmFont.toCharString());
        this.giveUpListenValueChange = false;
    }
}
